package com.zepher.springboot.service;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zepher.springboot.entity.Account;
import com.zepher.springboot.entity.Admin;
import com.zepher.springboot.exception.CustomException;
import com.zepher.springboot.mapper.AdminMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.Period;
import java.util.List;

@Service
public class AdminService {

    @Resource
    private AdminMapper adminMapper;

    /**
     * 查询所有用户
     * @param admin
     * @return
     */
    public List<Admin> selectAll(Admin admin) {
        List<Admin> list = adminMapper.selectAll(admin);
        return list;
    }

    /**
     * 根据用户ID查询单个用户
     * @param id 用户ID
     * @return
     */
    public Admin selectById(Integer id) {
        Admin admin = adminMapper.selectById(id);
        return admin;
    }

    /**
     * 分页查询
     */
    public PageInfo<Admin> selectPage(Integer pageNum, Integer pageSize, Admin admin) {
        PageHelper.startPage(pageNum, pageSize);
        List<Admin> list = adminMapper.selectAll(admin);
        PageInfo<Admin> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 新增用户
     */
    public void insert(Admin admin) {
        String username = admin.getUsername();
        Admin dbAdmin = adminMapper.selectByUsername(username);
        if (dbAdmin != null) {
            throw new CustomException("500", "用户已存在");
        }
        if (StrUtil.isBlank(admin.getPassword())){
            admin.setPassword("admin");
        }
        if (StrUtil.isBlank(admin.getName())){
            admin.setName(admin.getUsername());
        }
        if (StrUtil.isBlank(admin.getRole())){
            admin.setRole("admin");
        }
        adminMapper.insert(admin);
    }

    /**
     * 修改用户
     */
    public void update(Admin admin) {
        adminMapper.update(admin);
    }

    /**
     * 删除用户
     */
    public void delete(Integer id) {
        adminMapper.delete(id);
    }

    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            adminMapper.delete(id);
        }
    }

    /**
     * 登录
     */
    public Admin login(Account account) {
        String username = account.getUsername();
        Admin dbAdmin = adminMapper.selectByUsername(username);
        if (dbAdmin == null) {
            throw new CustomException("500", "用户不存在");
        }
        // 数据库存在这个账号
        String password = account.getPassword();
        if (!dbAdmin.getPassword().equals(password)) {
            throw new CustomException("500", "账号或密码错误");
        }
        return dbAdmin;
    }
}
